package com.kalaqia.gradle.jiagu

import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.tasks.TaskAction

class JiaGu360Task extends DefaultTask {
    JiaGu360Extension configuration
    def android
    def buildConfigs = []

    JiaGu360Task() {
        description = 'Assemble Resource Proguard APK'
        group = 'jiaGu360'
        outputs.upToDateWhen { false }
        android = project.extensions.android
        configuration = project.jiaGu360

        android.applicationVariants.all { variant ->
            variant.outputs.each { output ->

                String variantName = this.name["jiaGu360".length()..-1]
                if (variantName.equalsIgnoreCase(variant.buildType.name as String)
                        || isTargetFlavor(variantName, variant.productFlavors, variant.buildType.name)
                ) {

                    def baseName = variant.baseName.replaceAll("-", "/")
                    def outputPath = "${configuration.outputBasePath}/${baseName}";
                    def assembleTask = variant.assemble

                    if (configuration.archiveOutputEnable) {
                        assembleTask.doLast {
                            project.copy {
                                from output.outputFile
                                into project.file("${outputPath}/")
                            }
                        }
                    }

                    buildConfigs << new BuildInfo(
                            new File(outputPath, output.outputFile.name),
                            project.file("$outputPath/jiagu"),
                            variant.signingConfig,
                    )

                }

            }
        }

        if (!project.plugins.hasPlugin('com.android.application')) {
            throw new GradleException('generateARGApk: Android Application plugin required')
        }
    }

    static isTargetFlavor(variantName, flavors, buildType) {
        if (flavors.size() > 1) {
            String brand = flavors.get(0).name
            String env = flavors.get(1).name
            return variantName.equalsIgnoreCase([brand, env, buildType].join(""))
        }
        return false
    }

    @SuppressWarnings("GroovyUnusedDeclaration")
    @TaskAction
    run() {
        project.logger.info("[JiaGu360] configuartion:$configuration")

        buildConfigs.each { config ->
            project.logger.info("[JiaGu360] config:$config")
            RunGradleTask(config.loadApk, config.outputPath, config.signConfig)
        }

    }

    def RunGradleTask(def loadApk, def outputApk, def signingConfig) {
        def isSupportChannel = configuration.isSupportChannel ? "1" : "0";

        String result = String.format("%s %s %s %s",
                signingConfig.storeFile.path,
                signingConfig.keyPassword,
                signingConfig.keyAlias,
                signingConfig.storePassword,
        )

        if (configuration.getIsEnable()) {
            project.exec {
                ignoreExitValue true
                if (configuration.isMac) {
                    commandLine "sh", "${project.rootDir}/jiagu_mac/jiagu.sh", loadApk, outputApk, isSupportChannel
                } else {
                    commandLine "${project.rootDir}/360JiaGu/JiaGu.bat",             \
                                          loadApk, outputApk,              \
                                          isSupportChannel, configuration.getJiaGuJarPath(),            \
                                          configuration.getAccount(), configuration.getPassword(),           \
                                          result
                }
            }
        }
    }

}
